package cn.com.dhcc.app.pub.core.tag;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.util.StringUtils;

import cn.com.dhcc.app.core.CM;
import cn.com.dhcc.app.core.base.IocBean;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.tag.CommonTagEl;
import cn.com.dhcc.app.core.util.ReflectionUtil;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.pub.core.consts.AppConst;
import cn.com.dhcc.app.pub.core.consts.CT;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.turbo.entity.registry.AdapterBase;
import cn.com.dhcc.turbo.entity.registry.AdapterInfo;
import cn.com.dhcc.turbo.entity.registry.DataCategory;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.registry.OrgInfo;
import cn.com.dhcc.turbo.service.registry.AdapterInfoService;
import cn.com.dhcc.turbo.service.registry.BaseInfoService;
import cn.com.dhcc.turbo.service.registry.OrgInfoService;

/**
 * el 表达式
 *
 * @日期：2013-1-8下午3:01:27
 * @作者：乔兵
 * @版权所有：东华软件
 * @版本：1.0
 */
public class AppTagEl extends CommonTagEl {
	private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private static final  String DEFAULTSPLITCHAR = ",";
	/**
	 * 性别code-str转换 useage:${si:sex("1")} or ${si:sex(vo.sex)}
	 *
	 * @param code
	 * @return
	 */
	public static String sex(String code) {
		String sex = "";
		if ("1".equals(code)) {
			sex = "男";
		}
		if ("2".equals(code)) {
			sex = "女";
		}
		return sex;
	}

	/**
	 * 格式化日期
	 *
	 * @param date
	 * @return
	 */
	public static String fmtDate(Date date) {
		String dateStr = "";
		if (date != null) {
			dateStr = df.format(date);
		}
		return dateStr;
	}

	/**
	 * 创建下拉框的通用方法
	 *
	 * @param enumClass
	 * @param selectedCode
	 * @param excludeCode 排除的code ,号隔开
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static String ctoption(Class enumClass, String selectedCode, String excludeCodeStr) {
		EnumSet cts = EnumSet.allOf(enumClass);
		if (StringUtils.hasText(selectedCode))
			selectedCode = selectedCode.trim();
		StringBuilder rp = new StringBuilder();
		List<String> excludeCodes = new ArrayList<String>();
		if (StringUtils.hasText(excludeCodeStr)) {
			excludeCodes.addAll(Arrays.asList(excludeCodeStr.split(",")));
		}
		if (cts != null) {
			for (Iterator<Enum> iterator = cts.iterator(); iterator.hasNext();) {
				Enum em = (Enum) iterator.next();
				String code = (String) ReflectionUtil.getFieldValue(em, "code");
				if (excludeCodes.contains(code))
					continue;
				String name = (String) ReflectionUtil.getFieldValue(em, "name");
				rp.append("<option value=\"").append(code).append("\" ")
						.append(code.equalsIgnoreCase(selectedCode) ? "selected" : "").append(">").append(name)
						.append("</option>\r\n");
			}
		}
		return rp.toString();
	}

	/**
	 * 创建下拉框的通用方法
	 *
	 * @param enumClassName 在{@link CT}}里面注册过的码表的class名称
	 * @param selectedCode  已选择的code
	 * @param excludeCode 排除的code ,号隔开
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String ctoption(String enumClassName, String selectedCode, String excludeCodeStr) {
		Class enumClass = CT.CodeTablePool.get(enumClassName);
		return ctoption(enumClass, selectedCode, excludeCodeStr);
	}
    
	/**
	 * 创建下拉框的通用方法
	 *
	 * @param enumClassName 在{@link CT}}里面注册过的码表的class名称
	 * @param selectedCode  已选择的code
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String ctoption(String enumClassName, String selectedCode) {
		Class enumClass = CT.CodeTablePool.get(enumClassName);
		return ctoption(enumClass, selectedCode, null);
	}

	/**
	 * 根据给定的code获取name
	 *
	 * @param enumClassName
	 * @param selectedCode
	 * @return
	 */
	public static String ctname(String enumClassName, String selectedCode) {
		Class<?> enumClass = CT.CodeTablePool.get(enumClassName);
		return getNameFromCode(enumClass, selectedCode);
	}
	/**
	 * 根据给定的code获取name
	 *
	 * @param enumClassName
	 * @param selectedCodeMulti 多个code 以splitChar分隔
	 * @param splitChar 分隔符
	 * @return
	 */
	public static String ctnameMulti(String enumClassName, String selectedCodeMulti,String splitChar) {
		if(!StrUtil.isNotBank(selectedCodeMulti))return selectedCodeMulti;
		if(!StrUtil.isNotBank(splitChar))splitChar = DEFAULTSPLITCHAR;
		Class<?> enumClass = CT.CodeTablePool.get(enumClassName);
		String[] codes = selectedCodeMulti.split("\\"+splitChar);
		StringBuffer res = new StringBuffer();
		for (int i = 0; i < codes.length; i++) {
			res.append(getNameFromCode(enumClass, codes[i]));
			if(i<codes.length-1)res.append(splitChar);
		}
		return res.toString();
	}
	/**
	 * 根据给定的code获取name
	 *
	 * @param enumClassName
	 * @param selectedCodeMulti 多个code 以splitChar分隔
	 * @param splitChar 分隔符
	 * @return
	 */
	public static String ctnameMulti(String enumClassName, String selectedCodeMulti) {
		if(!StrUtil.isNotBank(selectedCodeMulti))return selectedCodeMulti;
		String splitChar = DEFAULTSPLITCHAR;
		Class<?> enumClass = CT.CodeTablePool.get(enumClassName);
		String[] codes = selectedCodeMulti.split("\\"+splitChar);
		StringBuffer res = new StringBuffer();
		for (int i = 0; i < codes.length; i++) {
			res.append(getNameFromCode(enumClass, codes[i]));
			if(i<codes.length-1)res.append(splitChar);
		}
		return res.toString();
	}
	@SuppressWarnings({ "rawtypes" })
	public static String getNameFromCode(Class enumClass, String selectedCode) {
		return getNameFromCode(enumClass, selectedCode, "code", "name");
	}
	/**
	 * 
	 * @param enumClass
	 * @param selectedCode
	 * @param codeFieleName code 映射 属性名称
	 * @param nameFieldName name  映射 属性名称
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String getNameFromCode(Class enumClass, String selectedCode,String codeFieleName,String  nameFieldName) {
		EnumSet cts = EnumSet.allOf(enumClass);
		if (cts != null || !StringUtils.hasText(selectedCode)) {
			for (Iterator<Enum> iterator = cts.iterator(); iterator.hasNext();) {
				Enum em = (Enum) iterator.next();
				String code = (String) ReflectionUtil.getFieldValue(em, codeFieleName);
				if (selectedCode.trim().equalsIgnoreCase(code)) {
					String name = (String) ReflectionUtil.getFieldValue(em, nameFieldName);
					return name;
				}
			}
		}
		return "";
	}
	/**
	 * 
	 * @param enumClass
	 * @param selectedCode
	 * @param codeFieleName code 映射 属性名称
	 * @param nameFieldName name  映射 属性名称
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Enum getEnumFromCode(Class enumClass, String selectedCode) {
		EnumSet cts = EnumSet.allOf(enumClass);
		if (cts != null || !StringUtils.hasText(selectedCode)) {
			for (Iterator<Enum> iterator = cts.iterator(); iterator.hasNext();) {
				Enum em = (Enum) iterator.next();
				String code = (String) ReflectionUtil.getFieldValue(em, "code");
				if (selectedCode.trim().equalsIgnoreCase(code)) {
					return em;
				}
			}
		}
		return null;
	}
	/**
	 * 根据节点获取节点名称
	 *
	 * @param nodeCode
	 * @return
	 */
	public static String nodeName(String nodeCode) {
		String nodeName = "";
		try {
			if (StrUtil.isNotBlank(nodeCode)) {
				BaseInfoService baseInfoService = (BaseInfoService) CM
						.getBeanByName(IocBean.BASE_INFO_SERVICEIMPL_BEAN);
				String[] nodes = nodeCode.split(",");
				Map<String, String> nodeMap = new HashMap<String, String>();//去重
				for (String node : nodes) {
					nodeMap.put(node, node);
				}
				for (Map.Entry<String, String> entry : nodeMap.entrySet()) {
					NodeInfo nodeInfo = baseInfoService.getNodeInfoByCode(entry.getKey());
					if (nodeInfo != null) {
						nodeName += nodeInfo.getNodeName() + ",";
					}else{
						nodeName += entry.getKey() + ",";
					}
				}
				nodeName = StrUtil.substringBeforeLast(nodeName, ",");
			}
		} catch (Exception e) {
			//ignored
		}
		return nodeName;
	}
	/**
	 * 根据适配器编码获取适配器类型
	 *
	 * @param dataCode
	 * @return
	 */
	public static String orgName(String orgCode) {
		try {
			if (StrUtil.isNotBlank(orgCode)) {
				OrgInfoService service = (OrgInfoService) CM
						.getBean(OrgInfoService.class);
					OrgInfo orgInfo=service.get(orgCode);
					if (orgInfo!=null ) {
						return orgInfo.getAdNm();
					}
			}
		} catch (Exception e) {
			//ignored
		}
		return "";
	}
	
	
	/**
	 * 根据适配器编码获取适配器类型
	 *
	 * @param dataCode
	 * @return
	 */
	public static String adaptorType(String adaptorCode) {
		try {
			if (StrUtil.isNotBlank(adaptorCode)) {
				BaseInfoService baseInfoService = (BaseInfoService) CM
						.getBeanByName(IocBean.BASE_INFO_SERVICEIMPL_BEAN);
					AdapterBase adapterInfo=baseInfoService.getAdapterBase(adaptorCode);
					if (adapterInfo.getAdapterType().equals(AppConst.OBJECT_TYPE.GLOBAL.getCode())) {
						return AppConst.OBJECT_TYPE.GLOBAL.getName();
					}else{
						return AppConst.OBJECT_TYPE.PARTIAL.getName();
					}
			}
		} catch (Exception e) {
			//ignored
		}
		return "";
	}
	
	/**
	 * 根据适配器编码获取对应的适配器个数
	 *
	 * @param dataCode
	 * @return
	 */
	public static String adaptorNum(String adaptorCode) {
		try {
			if (StrUtil.isNotBlank(adaptorCode)) {
				AdapterInfoService service=(AdapterInfoService) CM.getBean(AdapterInfoService.class);
//				BaseInfoService baseInfoService = (BaseInfoService) CM
//						.getBeanByName(IocBean.BASE_INFO_SERVICEIMPL_BEAN);
				WhereCondition condition = new WhereCondition();
				condition.where().eq("islocal", "0").and().eq("ADAPTER_CODE", adaptorCode).and().isNotNull("WSDL_URL");
				List<AdapterInfo> list = service.list(condition);
				if (list==null || list.isEmpty()) {
					return "0";
				}
				return list.size()+"";
			}
		} catch (Exception e) {
			//
		}
		return "0";
	}


	
	
	/**
	 * 根据数据分类编码获取数据名称
	 *
	 * @param dataCode
	 * @return
	 */
	public static String dataName(String dataCode) {
		String dataName = "";
		try {
			if (StrUtil.isNotBlank(dataCode)) {
				BaseInfoService baseInfoService = (BaseInfoService) CM
						.getBeanByName(IocBean.BASE_INFO_SERVICEIMPL_BEAN);
				String[] dataList = dataCode.split(",");
				Map<String, String> dataMap = new HashMap<String, String>();//去重
				for (String sys : dataList) {
					dataMap.put(sys, sys);
				}
				for (Map.Entry<String, String> entry : dataMap.entrySet()) {
					DataCategory dataCategory=baseInfoService.getDataCategoryByCode(entry.getKey());
					if (dataCategory != null) {
						dataName += dataCategory.getDataName() + ",";
					}else{
						dataName += entry.getKey() + ",";
					}
				}
				dataName = StrUtil.substringBeforeLast(dataName, ",");
			}
		} catch (Exception e) {
			//ignored
		}
		return dataName;
	}
	
	
	/**
	 * 根据适配器编码获取适配器名称
	 *
	 * @param dataCode
	 * @return
	 */
	public static String adaptorName(String adaptorCode) {
		String adaptorName = "";
		try {
			if (StrUtil.isNotBlank(adaptorCode)) {
				BaseInfoService baseInfoService = (BaseInfoService) CM
						.getBeanByName(IocBean.BASE_INFO_SERVICEIMPL_BEAN);
				String[] dataList = adaptorCode.split(",");
				Map<String, String> adaptorMap = new HashMap<String, String>();//去重
				for (String sys : dataList) {
					adaptorMap.put(sys, sys);
				}
				for (Map.Entry<String, String> entry : adaptorMap.entrySet()) {
					AdapterBase adapterInfo=baseInfoService.getAdapterBase(entry.getKey());
					if (adapterInfo != null) {
						adaptorName += adapterInfo.getAdapterName() + ",";
					}else{
						adaptorName += entry.getKey() + ",";
					}
				}
				adaptorName = StrUtil.substringBeforeLast(adaptorName, ",");
			}
		} catch (Exception e) {
			//ignored
		}
		return adaptorName;
	}

	/**
	 * 数据发送状态
	 *
	 * @param status
	 * @return
	 */
	public static String sendStatus(String status) {
		String desc = "";
		try {
			if (StrUtil.isNotBlank(status)) {
				desc=getNameFromCode(AppConst.SendStatus.class, status, "status", "desc");
				if ("".equals(desc)) {
					desc="状态未定义";
				}
			}
		} catch (Exception e) {
			//ignored
		}
		return desc;
	}
	/**
	 * 数据发送状态
	 *
	 * @param status
	 * @return
	 */
	public static String processStatus(String status) {
		String desc = "";
		try {
			if (StrUtil.isNotBlank(status)) {
				desc=getNameFromCode(AppConst.ProcessStatus.class, status, "type", "desc");
				if ("".equals(desc)) {
					desc="状态未定义";
				}
			}
		} catch (Exception e) {
			//ignored
		}
		return desc;
	}
	
	
	
	/**
	 * 数据通知状态
	 *
	 * @param status
	 * @return
	 */
	public static String uploadProcessStatus(String status) {
		String desc = "";
		try {
			if (StrUtil.isNotBlank(status)) {
				desc=getNameFromCode(AppConst.UploadProcessStatus.class, status, "type", "desc");
				if ("".equals(desc)) {
					desc="状态未定义";
				}
			}
		} catch (Exception e) {
			//ignored
		}
		return desc;
	}
	/**
	 * 数据通知状态
	 *
	 * @param status
	 * @return
	 */
	public static String msgType(String msgType) {
		String name = "";
		try {
			if (StrUtil.isNotBlank(msgType)) {
				if (AppConst.MsgType.SINGLE_MSG.value().equals(msgType)) {
					name = AppConst.MsgType.SINGLE_MSG.getDesc();
				}
				if (AppConst.MsgType.GROUP_MSG.value().equals(msgType)) {
					name = AppConst.MsgType.GROUP_MSG.getDesc();
				}
				if (AppConst.MsgType.SUB_MSG.value().equals(msgType)) {
					name = AppConst.MsgType.SUB_MSG.getDesc();
				}
			}
		} catch (Exception e) {
			//ignored
		}
		return name;
	}

	/**
	 * 数据通知状态
	 *
	 * @param status
	 * @return
	 */
	public static String notifyStatus(String status) {
		String name = "";
		try {
			if (StrUtil.isNotBlank(status)) {
				if (AppConst.NotifyStatus.READY.value().equals(status)) {
					name = AppConst.NotifyStatus.READY.getDesc();
				}
				if (AppConst.NotifyStatus.NOTIFIED.value().equals(status)) {
					name = AppConst.NotifyStatus.NOTIFIED.getDesc();
				}
				if (AppConst.NotifyStatus.NOTIFYING.value().equals(status)) {
					name = AppConst.NotifyStatus.NOTIFYING.getDesc();
				}
				if (AppConst.NotifyStatus.FAIL.value().equals(status)) {
					name = AppConst.NotifyStatus.FAIL.getDesc();
				}
			}
		} catch (Exception e) {
			//ignored
		}
		return name;
	}
//	public static void main(String[] args) {
//		System.err.println(ctnameMulti("ALERT_PIPELINE", "1,2,80", ""));
	//System.out.println(desc);
//	}
	
	
	/**
	 * 格式化文件名称
	 * @param filename
	 * @return
	 */
	public static String formatterFile(String filename) {
		StringBuffer sb=new StringBuffer();
		String[] filenames=filename.split(",");
		String str=null;
		for (int i=0;i<filenames.length;i++) {
			int index=filenames[i].lastIndexOf("/");
			if (index>=0) {
				str=filenames[i].substring(index+1);
			}else{
				str=filenames[i];
			}
			if (i==filenames.length) {
				sb.append(str);
			}else{
				sb.append(str+"<br/>");
			}
		}
		return sb.toString();
	}
	
	/**
	 * 判断是否是内网
	 * @param netType
	 * @return
	 */
	public static boolean isInnerNet(String netType){
		if (netType.equals(NodeInfoParam.NET_TYPE.INNER.getCode())) {
			return true;
		}
		return false;
	}
}
